package com.example.chronicdisease.service;

import com.example.chronicdisease.mapper.UsersMapper;
import com.example.chronicdisease.pojo.Users;
import com.example.chronicdisease.response.ApiRestResponse;
import com.example.chronicdisease.response.ChronicDiseaseException;
import com.example.chronicdisease.response.ChronicDiseaseExceptionEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;



@Service
public class UsersServiceImpl implements UsersService {
    @Autowired
    UsersMapper usersMapper;
    //处理登录业务
    //调用mapper中的方法查询该用户是否存在，存在返回该用户数据，不存在报错
    @Override
    public Users login(Users users){
        Users user=usersMapper.selectByPrimaryKey(users.getUserId());
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();

        if(user!=null && encoder.matches(users.getPassword(), user.getPassword())){
            encodePass(users);
            return user;
        }else {
            //不存在抛出异常
            throw new ChronicDiseaseException(ChronicDiseaseExceptionEnum.PHONE_OR_PASSWORD_IS_WRONG);
        }
    }

    @Override
    public ApiRestResponse register(Users users){

        Users u = usersMapper.selectByPrimaryKey(users.getUserId());
        if (u != null) {
            throw new ChronicDiseaseException(ChronicDiseaseExceptionEnum.USER_IS_EXIST);
        }else {
            users.setUserType(1);
            // 对密码和身份证号进行加密
            encodePass(users);
            usersMapper.insert(users);
        }
        return ApiRestResponse.success();
    }

    public void encodePass(Users user){
        String oldPass = user.getPassword();
        BCryptPasswordEncoder ENC = new BCryptPasswordEncoder();
        String newPass = ENC.encode(oldPass);
        user.setPassword(newPass);

    }

    @Override
    public ApiRestResponse updatepass(Users users) {
        Users u = usersMapper.selectByPrimaryKey(users.getUserId());

        // 验证用户是否存在，并且身份证号是否匹配
        if (u != null && users.getIdentityCard().equals(u.getIdentityCard())) {
            encodePass(users);
            usersMapper.updateByPrimaryKeySelective(users);
        }else {
            throw new ChronicDiseaseException(ChronicDiseaseExceptionEnum.USER_NO_EXIST);
        }
        return ApiRestResponse.success();
    }

    @Override
    public Users getUser(Users users) {
        Users u = usersMapper.selectByPrimaryKey(users.getUserId());
        return u;
    }

    @Override
    public Users select(String userId) {

        Users users=usersMapper.selectByPrimaryKey(userId);
        System.out.println("这是用户"+users);
        return users;
    }

}
